package com.cmcc.migu.cmmon.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

public class AESUtil {
	
	private static Map<String, AESUtil> AESUtilMap = new HashMap<String, AESUtil>();

	/** 加密工具 */
	private Cipher encryptCipher = null;

	/** 解密工具 */
	private Cipher decryptCipher = null;

	public static AESUtil getInstance(String key) throws Exception {
		if(!AESUtilMap.containsKey(key)){
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(key.getBytes("UTF8"));
			AESUtilMap.put(key, new AESUtil(byteArr2HexStr(md5.digest()).substring(0, 16)));
		}
		return AESUtilMap.get(key);
	}

	private AESUtil(String keyvalue) throws Exception {
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		if (keyvalue == null)
			throw new Exception("key is null");
		byte[] arrBTmp = null;
		try {
			arrBTmp = keyvalue.getBytes("UTF8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		// 创建一个空的length位字节数组（默认值为0）
		byte[] arrB = new byte[16];

		// 将原始字节数组转换为8位
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		// 生成密钥
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "AES");

		// 生成Cipher对象,指定其支持的DES算法
		try {
//			密钥必须是16位的
//			待加密内容的长度必须是16的倍数
			//Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
			//Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 
			
			encryptCipher = Cipher.getInstance("AES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);

			decryptCipher = Cipher.getInstance("AES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对字符串加密
	 * 
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public String encrytor(String str) throws Exception {
		byte[] src = null;
		try {
			src = str.getBytes("UTF8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return byteArr2HexStr(encryptCipher.doFinal(src)).toUpperCase();
	}

	/**
	 * 对字符串解密
	 * 
	 * @param buff
	 * @return
	 * @throws Exception
	 */
	public String decryptor(String str) throws Exception {
		return new String(decryptCipher.doFinal(hexStr2ByteArr(str.toLowerCase())), "UTF8");
	}

	/**
	 * 将byte数组转换为表示16进制值的字符串， 如：byte[]{8,18}转换为：0813， 和public static byte[]
	 * hexStr2ByteArr(String strIn) 互为可逆的转换过程
	 * 
	 * @param arrB
	 *            需要转换的byte数组
	 * @return 转换后的字符串
	 * @throws Exception
	 *             本方法不处理任何异常，所有异常全部抛出
	 */
	public static String byteArr2HexStr(byte[] arrB) {
		int iLen = arrB.length;
		// 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			// 把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小于0F的数需要在前面补0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	/**
	 * 将表示16进制值的字符串转换为byte数组， 和public static String byteArr2HexStr(byte[] arrB)
	 * 互为可逆的转换过程
	 * 
	 * @param strIn
	 *            需要转换的字符串
	 * @return 转换后的byte数组
	 * @throws Exception
	 *             本方法不处理任何异常，所有异常全部抛出
	 */
	public static byte[] hexStr2ByteArr(String strIn) {
		byte[] arrB = null;
		try {
			arrB = strIn.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int iLen = arrB.length;

		// 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = "";
			try {
				strTmp = new String(arrB, i, 2,"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}

}